<template>
	<a-drawer
		:title="formData.id ? '编辑' : '增加'"
		:width="500"
		:visible="visible"
		:destroy-on-close="true"
		:body-style="{ paddingBottom: '80px' }"
		:footer-style="{ textAlign: 'right' }"
		@close="onClose"
	>
		<a-tabs v-model:activeKey="activeKey">
			<a-tab-pane key="data" tab="券信息" force-render>
				<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
					<a-form-item label="券名称：" name="title">
						<a-input :disabled="readonly" v-model:value="formData.title" placeholder="请输入券名称" allow-clear />
					</a-form-item>
					<a-form-item label="券类型：" name="couponType">
						<a-select
							:disabled="formData.id"
							v-model:value="formData.couponType"
							:options="couponTypeOptions"
							placeholder="请选择券类型"></a-select>
					</a-form-item>
					<a-form-item label="券描述：" name="description">
						<a-input :disabled="readonly" v-model:value="formData.description" placeholder="描述信息，用于向用户展示优惠券"/>
					</a-form-item>
					<a-form-item v-if="formData.couponType === 'CRM_COUPON'" label="面额类型：" name="valueType">
						<a-radio-group
							:disabled="formData.id"
							v-model:value="formData.valueType"
							:options="valueTypeOptions"></a-radio-group>
					</a-form-item>
					<a-form-item v-if="formData.couponType === 'CRM_COUPON'"  label="券面额：" name="value">
						<a-input-number
							:disabled="formData.id"
							v-model:value="formData.value"
							style="width: 160px;"
							:min="0"
							placeholder="请输入券面额">
							<template #addonAfter>
								{{ formData.valueType === 'AMOUNT' ? '元' : '折'}}
							</template>
						</a-input-number>
					</a-form-item>
					<a-form-item v-if="formData.couponType === 'CRM_COUPON'" label="使用限制：" name="useCondition">
						<a-input-number
							:disabled="formData.id"
							style="width: 160px;"
							:min="0"
							v-model:value="formData.useCondition">
							<template #addonAfter>元</template>
						</a-input-number>
					</a-form-item>
					<a-form-item label="用户限制：" name="userType">
						<a-radio-group
							:disabled="readonly"
							v-model:value="formData.userType"
							:options="userTypeOptions"></a-radio-group>
					</a-form-item>
					<a-form-item label="发券方式：" name="issueType">
						<a-radio-group
							:disabled="formData.id"
							v-model:value="formData.issueType">
							<a-radio :value="0">立即发放</a-radio>
							<a-radio :value="1">领券后发放</a-radio>
							<a-radio :value="2">消费后发放</a-radio>
						</a-radio-group>
					</a-form-item>
					<a-form-item label="发券数量：" name="issueCount">
						<a-input-number :disabled="readonly" :min="0" v-model:value="formData.issueCount" style="width: 160px"/>
					</a-form-item>
					<a-form-item label="发放条件" v-if="formData.issueType === 2" name="issueCondition">
						<a-input-number :disabled="readonly"  :min="0.01" v-model:value="formData.issueCondition" style="width: 160px">
							<template #addonAfter>元</template>
						</a-input-number>
					</a-form-item>
					<div>
						<div class="ant-form-item-label block">活动日期：</div>
						<a-space>
							<a-form-item name="startTime">
								<a-date-picker :disabled="readonly" format="YYYY-MM-DD" v-model:value="formData.startTime"></a-date-picker>
							</a-form-item>
							<a-form-item >
								至
							</a-form-item>
							<a-form-item name="endTime">
								<a-date-picker :disabled="readonly"  format="YYYY-MM-DD" v-model:value="formData.endTime"></a-date-picker>
							</a-form-item>
						</a-space>
					</div>
					<a-form-item label="有效期：" name="effectDateType">
						<a-radio-group
							:disabled="readonly"
							v-model:value="formData.effectDateType">
							<a-radio value="FIXED">固定日期</a-radio>
							<a-radio value="RECEIVE">有效天数</a-radio>
						</a-radio-group>
					</a-form-item>
					<a-form-item v-if="formData.effectDateType === 'FIXED'">
						<a-date-picker :disabled="readonly" format="YYYY-MM-DD" v-model:value="formData.useStartTime"></a-date-picker>
						至
						<a-date-picker :disabled="readonly" format="YYYY-MM-DD" v-model:value="formData.useEndTime"></a-date-picker>
					</a-form-item>
					<a-form-item v-else>
						<a-input-number :disabled="readonly" style="width: 160px" :min="0" v-model:value="formData.effectDays">
							<template #addonAfter>天</template>
						</a-input-number>
					</a-form-item>
					<a-form-item label="活动门店：" name="storeScope">
						<a-radio-group
							:disabled="readonly"
							class="mb-4"
							@change="onStoreScopeOptionChange"
							v-model:value="formData.storeScopeOption">
							<a-radio value="ALL">全部机构</a-radio>
							<a-radio value="CUSTOM">选定机构</a-radio>
						</a-radio-group>
						<a-select :disabled="readonly" v-if="formData.storeScopeOption === 'CUSTOM'" mode="multiple" v-model:value="formData.storeScope" :options="storeOptions"/>
<!--						<a-tree-select-->
<!--							v-if="formData.storeScopeOption === 'CUSTOM'"-->
<!--							v-model:value="formData.storeScope"-->
<!--							style="width: 100%"-->
<!--							:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"-->
<!--							placeholder="请选择活动门店"-->
<!--							allow-clear-->
<!--							multiple-->
<!--							tree-default-expand-all-->
<!--							:tree-data="treeData"-->
<!--							:field-names="{-->
<!--								children: 'children',-->
<!--								label: 'name',-->
<!--								value: 'id'-->
<!--							}"-->
<!--							selectable="false"-->
<!--							tree-line-->
<!--						></a-tree-select>-->
					</a-form-item>
					<a-form-item label="使用说明：" name="note">
						<a-textarea :disabled="readonly" show-count v-model:value="formData.note" :rows="4"/>
					</a-form-item>
				</a-form>
			</a-tab-pane>
			<a-tab-pane key="items" tab="活动商品" force-render>
				<a-radio-group
					class="mb-4"
					v-model:value="formData.goodScopeOption">
					<a-radio value="ALL">全品类</a-radio>
					<a-radio value="CATEGORY">指定品类</a-radio>
					<a-radio value="GOOD">单品券</a-radio>
				</a-radio-group>
			</a-tab-pane>
		</a-tabs>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="submitLoading" @click="onSubmit" :disabled="readonly">保存</a-button>
		</template>
		<Icon-selector ref="iconSelector" @iconCallBack="iconCallBack" />
	</a-drawer>
</template>

<script setup name="crmCardTypeForm">
	import { message } from 'ant-design-vue'
	import dayjs from "dayjs"
	import {required} from '@/utils/formRules'
	import IconSelector from '@/components/Selector/iconSelector.vue'
	import crmApi from '@/api/crm/crmApi'
	import { getCurrentInstance } from 'vue'
	import tool from "@/utils/tool";
	import orgApi from "@/api/sys/orgApi";
	// 默认是关闭状态
	let visible = $ref(false)
	let readonly = $ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const formData = ref({})
	const submitLoading = ref(false)
	const iconSelector = ref()
	// 定义机构元素
	const treeData = ref([])
	const activeKey = ref('data')
	const onStoreScopeOptionChange = ({ target }) => {
		if (target.value === 'CUSTOM') {
			formData.value.storeScope = []
		}
	}
	// 打开抽屉
	const onOpen = (record, _readonly = false) => {
		visible = true
		readonly = _readonly
		formData.value = {
			status: '0',
			goodScopeOption: 'ALL',
			storeScopeOption: 'ALL',
			issueType: 0,
			useType: 'ALL',
			goodScope: 'ALL',
			issueCondition: 0,
			valueType: 'AMOUNT',
			effectDateType: 'FIXED',
			sortCode: 99,
			storeScope: 0
		}
		// 获取机构树并加入顶级
		// orgApi.orgTree({ category: 'STORE' }).then((res) => {
		// 	treeData.value = [
		// 		{
		// 			id: 0,
		// 			parentId: '-1',
		// 			name: '所有机构',
		// 			children: res,
		// 			disabled: true
		// 		}
		// 	]
		// })
		if (record) {
			formData.value = Object.assign({}, record)
			if (formData.value.storeScope === 'ALL') {
				formData.value.storeScopeOption = 'ALL'
			} else {
				formData.value.storeScopeOption = 'CUSTOM'
				formData.value.storeScope = formData.value.storeScope.split(',')
				formData.value.useStartTime = null
				formData.value.useEndTime = null
			}
			if (formData.value.goodScope === 'ALL') {
				formData.value.goodScopeOption = 'ALL'
			}
			if (formData.value.useStartTime) {
				formData.value.useStartTime = dayjs(formData.value.useStartTime)
			}
			if (formData.value.useEndTime) {
				formData.value.useEndTime = dayjs(formData.value.useEndTime)
			}
			if (formData.value.startTime) {
				formData.value.startTime = dayjs(formData.value.startTime)
			}
			if (formData.value.endTime) {
				formData.value.endTime = dayjs(formData.value.endTime)
			}
		}
	}
	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		visible = false
	}

	// 默认要校验的
	const formRules = {
		couponType: [required('请选择券类型')],
		valueType: [required('请选择面额类型')],
		title: [required('请输入活动标题')],
		status: [required('请选择卡状态')],
		cardType: [required('请选择卡类型')],
	}

	// 图标选择器回调
	const iconCallBack = (value) => {
		formData.value.icon = value
	}
	const { proxy } = getCurrentInstance()
	let couponTypeOptions = proxy.$TOOL
		.dictTypeList('COUPON_TYPE')
		.map((item) => {
			return {
				value: item['dictValue'],
				label: item['name']
			}
		})
	let valueTypeOptions = tool
		.dictTypeList('COUPON_VALUE_TYPE')
		.map((item) => {
			return {
				value: item['dictValue'],
				label: item['name']
			}
		})
	let userTypeOptions = tool
		.dictTypeList('COUPON_USER_TYPE')
		.map((item) => {
			return {
				value: item['dictValue'],
				label: item['name']
			}
		})
	let storeOptions = tool
		.tableList('ORG_CATEGORY')
		.filter(item => item.category === 'STORE')
		.map(item => {
			return {
				value: item['code'],
				label: item['name']
			}
		})
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				const param = parameterChanges(formData.value)
				if (!param.startTime || !param.endTime) {
					message.error('请选择正确的活动日期')
					return
				}
				param.startTime = dayjs(param.startTime).format('YYYY-MM-DD')
				param.endTime = dayjs(param.endTime).format('YYYY-MM-DD')
				if (param.useStartTime) {
					param.useStartTime = dayjs(param.useStartTime).format('YYYY-MM-DD')
				}
				if (param.useEndTime) {
					param.useEndTime = dayjs(param.useEndTime).format('YYYY-MM-DD')
				}
				if (param.storeScopeOption === 'ALL') {
					param.storeScope = 'ALL'
				} else {
					param.storeScope = param.storeScope.join(',')
				}
				submitLoading.value = true
				crmApi.couponActivitySubmitForm(param, param.id).then(() => {
					visible = false
					emit('successful')
				}).finally(() => {
					submitLoading.value = false
				})
			})
	}
	const parameterChanges = (data) => {
		return Object.assign({}, data)
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
